package com.example.loopyserver.exception;

import com.example.loopyserver.common.CommonResult;
import com.example.loopyserver.common.ResultCode;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.LinkedList;


@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(value = CommonException.class)
    public CommonResult<Void> handleCommonException(CommonException e) {
        return CommonResult.error(e.code, e.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        Object[] arguments = e.getDetailMessageArguments();
        if (arguments != null) {
            LinkedList<String> errors = new LinkedList<>();
            for (Object argument : arguments) {
                String error = argument.toString();
                if (!error.isEmpty()) {
                    errors.add(error);
                }
            }
            if (!errors.isEmpty()) {
                String msg = ResultCode.ARGUMENT_NOT_VALID.defaultMsg + ": " + errors;
                return CommonResult.error(ResultCode.ARGUMENT_NOT_VALID, msg);
            }
        }
        return CommonResult.error(ResultCode.ARGUMENT_NOT_VALID);
    }
}